<?php
namespace app\common\library;
class ImageUploadOptimizer
{
    private $batchSize = 5;
    private $delayBetweenBatches = 2; // 秒
    
    public function processImages($imageUrls, $shops, $product_id, $shop_id, $method, $accessToken)
    {
        $data = [];
        $batches = array_chunk($imageUrls, $this->batchSize, true);
        
        foreach ($batches as $batchIndex => $batchUrls) {
            $batchResults = $this->processBatch(
                $batchUrls, 
                $shops, 
                $product_id, 
                $shop_id, 
                $method, 
                $accessToken
            );
            
            $data = array_merge($data, $batchResults);
            
            // 不是最后一批时休息
            if ($batchIndex < count($batches) - 1) {
                sleep($this->delayBetweenBatches);
            }
        }
        
        return $data;
    }
    
    private function processBatch($batchUrls, $shops, $product_id, $shop_id, $method, $accessToken)
    {
        $results = [];
        
        foreach ($batchUrls as $k => $v) {
            try {
                $result = $this->uploadSingleImage(
                    $v, $shops['name'], $product_id, $shop_id, $method, $accessToken
                );
                
                if ($result) {
                    $results[] = $result;
                }
                
            } catch (\Exception $e) {
                // 记录错误日志
                error_log("图片上传失败: {$v} - " . $e->getMessage());
            }
        }
        
        return $results;
    }
    
    private function uploadSingleImage($imageUrl, $shopName, $product_id, $shop_id, $method, $accessToken)
    {
        $base6 = addSlantedWatermarkToImageUrl($imageUrl, $shopName);
        $imageData = file_get_contents('https://zixingche.net/' . $base6);
        
        $base64 = base64_encode($imageData);
     
        $sysParams = [
            'method' => $method,
            'v' => '2.0',
            'access_token' => $accessToken,
            'timestamp' => round(microtime(true) * 1000),
            'funType' => 'albu',
            'imageBase64' => $base64,
            'imageBannerName' => '',
            'imageName' => $product_id . '-' . $shop_id . '.jpg'
        ];
        
        $res = post_crul($sysParams);
        unlink(root_path() . 'public' . $base6);
        
        if ($res['productImg']) {
            return [
                'l_imgurl' => $res['productImg']['l_imgurl'],
                'l_imgmd5' => $res['productImg']['l_imgmd5'],
                'l_localfilename' => $res['productImg']['l_localfilename'],
                'l_imgsize' => $res['productImg']['l_imgsize']
            ];
        }
        
        return null;
    }
}